package io;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import sql.SqlGenerator.Response;

public class MessageWriter {
	
	private static MessageWriter writer = new MessageWriter();
	private boolean isOpen = false;
	private FileWriter warningFileWriter;
	private FileWriter infoFileWriter;
	private FileWriter sqlFileWriter;
	
	private MessageWriter(){
		
	}

	public static MessageWriter getInstance(){
		return writer;
	}
	
	public void open(){
		isOpen = true;
		
		File waringFile = new File("waring.txt");
		if(waringFile.exists()){
			waringFile.delete();
		}
		File infoFile = new File("info.txt");
		if(infoFile.exists()){
			infoFile.delete();
		}
		File sqlFile = new File("schemaCreate.sql");
		if(sqlFile.exists()){
			sqlFile.delete();
		}
		try {
			warningFileWriter = new FileWriter("waring.txt", true);
			infoFileWriter =  new FileWriter("info.txt", true);
			sqlFileWriter = new FileWriter("schemaCreate.sql",true);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void close(){
		if(isOpen){
			isOpen = false;
			try {
				if(warningFileWriter != null){
					warningFileWriter.flush();
					warningFileWriter.close();
				}
				if(infoFileWriter != null){
					infoFileWriter.flush();
					infoFileWriter.close();
				}
				if(sqlFileWriter != null){
					sqlFileWriter.flush();
					sqlFileWriter.close();
				}
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	public void writeWarning(String message){
		try {
			if(!isOpen) open();
			warningFileWriter.write(message + "\r\n");
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void writeSql(String message){
		try {
			if(!isOpen) open();
			sqlFileWriter.write(message.replace("\t", "") + ";\r\n");
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void writeWarning(String tableName,Response rep){
		if(rep != null && rep.getMessage() != null && rep.getMessage().length() > 0){
			writeWarning(String.format("%s：%s", tableName,rep.getMessage()));
		}
	}
	
	public void writeInfo(String message){
		try {
			if(!isOpen) open();
			infoFileWriter.write(message + "\r\n");
			System.out.println(message);
			
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
